package creational.prototype;


import java.util.ArrayList;

/**
 * 原型模式（克隆）
 * 实现Cloneable接口，重写clone接口
 * 数组、容器对象、引用对象等另行拷贝
 */

class Product implements Cloneable{
    private String name;
    private String value;
    private ArrayList<String> types;

    public Product(String name, String value,ArrayList<String> types) {
        this.name = name;
        this.value = value;
        this.types = types;
    }

    @Override
    protected Product clone(){
        Product product = null;
        try{
           product = (Product) super.clone();
           //深拷贝
            product.types = (ArrayList<String>) this.types.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return product;
    }

    @Override
    public String toString() {
        return "Product{" +
                "name='" + name + '\'' +
                ", value='" + value + '\'' +
                ", types=" + types +
                '}';
    }

    public void addType(String type){
        if (types != null){
            types.add(type);
        }
    }
}


class Test{
    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();
        list.add("雪佛兰");
        list.add("奥迪");
        Product product = new Product("车车", "$20w",list);
        Product product1 = product.clone();
        product.addType("本田");
        System.out.println(product+"-->"+product.hashCode());
        System.out.println(product1+"-->"+product1.hashCode());
        System.out.println(product == product1);
    }
}
